package edu.hitsz.rank;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class RankDaoImpl implements RankDao{
    
    private List<RankInfo> rankInfoList;
    
    public RankDaoImpl(File file) throws NumberFormatException, IOException{
        rankInfoList = new ArrayList<>();
        
        BufferedReader reader = new BufferedReader(new FileReader(file));

        String line;
        while ((line = reader.readLine()) != null) {
            String[] data = line.split(" "); 
            if (data.length == 3) {
                
                String playerName = data[0];
                int playerScore = Integer.parseInt(data[1]);
                String date = data[2];

                rankInfoList.add(new RankInfo(playerName, playerScore, date));
            } else {
                System.err.println("Invalid data format: " + line);
            }
        }

    }

    @Override
    public List<RankInfo> getRankInfoList() {
        return rankInfoList;
    }

    @Override
    public void addRankInfo(RankInfo rankInfo) {
        rankInfoList.add(rankInfo);
    }
    @Override
    public void sortRankInfoList() {
        rankInfoList.sort((o1, o2) -> o2.getScore() - o1.getScore());
    }

    @Override
    public void saveRankInfoList(String fileName) {
        rankInfoList.sort((o1, o2) -> o2.getScore() - o1.getScore());
        File file = new File(fileName);
        
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (RankInfo rankInfo : rankInfoList) {
                writer.write(rankInfo.getUser_name() + " " + rankInfo.getScore() + " " + rankInfo.getCreate_time() + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void printRankInfoList() {
        
        System.out.println("*********************************");
        System.out.println("        Rank List       ");
        System.out.println("*********************************");
        for (RankInfo rankInfo : rankInfoList) {
            System.out.println(rankInfo.getUser_name() + " " + rankInfo.getScore() + " " + rankInfo.getCreate_time());
        }
    }
        
}
